package in.co.codedoc.idcontainer;

import in.co.codedoc.idcontainer.IdContainer.IdContainerId;
import in.co.codedoc.sql.DBMappedEntity;
import in.co.codedoc.sql.IDBase;

import java.util.ArrayList;

public class IdList<T extends IDBase>
	implements DBMappedEntity
{
	public IdList<T> SetId(IdListId<T> id)
	{
		this.id = id;
		
		return this;
	}

	public IdListId<T> GetId()
	{
		if(id == null)
		{
			Save();
		}
		
		return id;
	}
	
	@Override
	public void Reload()
	{
		IdContainer idContainer 
			= IdContainerId.Create(id.GetId()).Get();
		
		container.clear();
		
		idContainer.Copy(container);
	}
		
	public IdList<T> Add(T t)
	{
		id = null;
		container.add(t.GetId());
		return this;
	}
	
	public IdList<T> Set(int index,T t)
	{
		id = null;
		container.set(index,t.GetId());
		return this;
	}
	
	public IdList<T> Remove(int index)
	{
		id = null;
		container.remove(index);
		return this;
	}
	
	public IdList<T> Save()
	{
		if(id == null)
		{
			IdContainer idContainer
				= IdContainer.BindOrSave(container);
			
			id = IdListId.Create(idContainer.GetId().GetId());
		}
		
		return this;
	}
	
	private IdListId<T> id;
	private ArrayList<Long> container = new ArrayList<Long>();
}
